package com.duleme.servlet;

import com.duleme.common.EncodeUtils;
import com.duleme.dao.UserDao;
import com.duleme.entity.Captcha;
import com.duleme.service.CaptchaService;
import com.duleme.service.impl.CaptchaServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet(name = "AlterCaptchaServlet",urlPatterns = "/password/captcha")
public class AlterCaptchaServlet extends HttpServlet {
    UserDao userDao = new UserDao();
    Captcha captcha = new Captcha();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EncodeUtils.setEncoding(request,response);
        //System.out.println(request.getParameter("userAccount"));
        CaptchaService captchaService = new CaptchaServiceImpl();
        String userAccount = request.getParameter("userAccount");
        System.out.println(userAccount);
        PrintWriter writer = response.getWriter();
        if (!userDao.checkAccountValid(userAccount)){
            System.out.println("此用户可以修改密码");
            captcha.setUserAccount(userAccount);
            captcha.setCreateTime(new Date());
            captcha.setCode(captchaService.generateCaptcha());
            captcha.setExpire(15);
            request.getSession().setAttribute("phoneCaptcha",captcha);//向浏览器发送captcha
            captchaService.sendCaptcha(captcha.getUserAccount(),captcha.getCode(),captcha.getExpire());//向接口获取短信验证码
            System.out.println("手机号修改密码");
            System.out.println("验证码："+captcha.getCode());
            System.out.println("手机号："+captcha.getUserAccount());
            System.out.println("创建时间："+captcha.getCreateTime());
            System.out.println("验证码有效期："+captcha.getExpire());
            writer.print(1);//可以获取到
            writer.close();
        }
        else {
            writer.print(2);//无法获取到
            System.out.println("该手机号没有注册");
            writer.close();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
